#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int n,m,xx[4] = {
	0,0,1,-1
},yy[4] = {
	1,-1,0,0
},a_[2001][2001][2] = {
	0
};
char a[2001][2001];
typedef struct point{
	int x,y,step,getKey;
	point(int x,int y,int step,int getKey):x(x),y(y),step(step),getKey(getKey){
		
	}point(){
		
	}
}point;
point pp;
void bfs();
int main(){
	int i,j;
	cin>>n>>m;
	for(i = 1;i<=n;++i){
		for(j = 1;j<=m;++j){
			cin>>a[i][j];
			if(a[i][j]=='S'){
				pp = point(i,j,0,0);
				
			}
		}
	}bfs();
	return 0;
	
}void bfs(){
	queue<point>q;
	q.push(pp);
	while(!q.empty()){
		point p = q.front();
		if(a[p.x][p.y]=='T'&&p.getKey){
			cout<<p.step;
			return;
			
		}q.pop();
		for(int i = 0;i<4;++i){
			int tx = p.x+xx[i],ty = p.y+yy[i];
			if(tx>0&&tx<=n&&ty>0&&ty<=n&&a[tx][ty]!='#'&&!a_[tx][ty][p.getKey]){
				a_[tx][ty][p.getKey] = 1;
				if(a[tx][ty]=='P'){
					q.push(point(tx,ty,p.step+1,1));
					
				}else
					q.push(point(tx,ty,p.step+1,p.getKey));
				
			}
		}
	}
}